package www.dianbaozu.com.ui.chat.refuseList

import android.view.View
import androidx.fragment.app.viewModels
import com.luck.picture.lib.decoration.WrapContentLinearLayoutManager
import com.netease.nim.uikit.api.NIMHelper
import com.netease.nimlib.sdk.RequestCallbackWrapper
import com.netease.nimlib.sdk.ResponseCode
import kotlinx.coroutines.FlowPreview
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentRefuseListBinding
import www.dianbaozu.com.ui.chat.refuseList.adapter.RefuseListAdapter
import www.wen.com.common.lib.base.fragment.BaseLoadingFragment
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.extension.toast
import www.wen.com.common.lib.helper.loading.TitleBarUniversalAdapter

/**
 * @author WEN
 * @Description:好友请求拒绝列表
 * @date 2020//25 17:48
 */
class RefuseListFragment : BaseLoadingFragment<FragmentRefuseListBinding>() {

    private val refuseListViewModel: RefuseListViewModel by viewModels()

    private val adapter: RefuseListAdapter by lazy {
        RefuseListAdapter(
            dataBinding.rvRefuseList, R.layout.item_friend_refuse,
            mutableListOf()
        ) { position, userInfo ->
            if (position>=0) {
                NIMHelper.removeFromBlackList(userInfo.account,
                    object : RequestCallbackWrapper<Void>() {
                        override fun onResult(code: Int, result: Void?, exception: Throwable?) {
                            if (code != ResponseCode.RES_SUCCESS.toInt()) {
                                toast("解除屏蔽失败")
                                return
                            }
                            adapter.data.removeAt(position)
                            adapter.notifyItemRemoved(position)
                            if (adapter.data.isEmpty()) {
                                dataBinding.tvEmpty.visibility = View.VISIBLE
                            }
                        }
                    })
            }
        }
    }

    override val viewModel: BaseViewModel
        get() = refuseListViewModel

    override fun isEnableLoadingHelper(): Boolean = true

    override fun getTitleBarUniversalAdapter(): TitleBarUniversalAdapter =
        TitleBarUniversalAdapter(requireActivity(), "已屏蔽", action = ::titleAction)

    override fun getLayoutId(): Int = R.layout.fragment_refuse_list

    override fun lazyInitView() {
        dataBinding.apply {
            rvRefuseList.adapter = adapter
            rvRefuseList.layoutManager = WrapContentLinearLayoutManager(requireActivity())
        }
        getBlackListUsers()
    }

    @FlowPreview
    private fun getBlackListUsers() {
        refuseListViewModel.getBlackListUsers {
            if (it.data.isNotEmpty()) {
                adapter.setNewData(it.data)
                dataBinding.tvEmpty.visibility = View.GONE
            }
        }
    }

}



